package cn.ruituo.util;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.ibatis.cache.Cache;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author oldliu
 * @since 1.0
 */
public class RedisCache implements Cache {
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Jedis redisClient=createRedis();
    private String id;

    public RedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        LogUtil.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id="+id);
        this.id = id;
    }
    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public int getSize() {

        return Integer.valueOf(redisClient.dbSize().toString());
    }

    @Override
    public void putObject(Object key, Object value) {
        LogUtil.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value);
        redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));
    }

    @Override
    public Object getObject(Object key) {
        Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));
        LogUtil.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:"+key+"="+value);
        return value;
    }

    @Override
    public Object removeObject(Object key) {
        return redisClient.expire(SerializeUtil.serialize(key.toString()),0);
    }

    @Override
    public void clear() {
        redisClient.flushDB();
        //redisClient.close();
    }
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
    protected  static Jedis createRedis(){
        ///JedisPool pool = new JedisPool( "127.0.0.1",6379);
        JedisPool pool = new JedisPool( new GenericObjectPoolConfig(),"127.0.0.1",6379);
        Jedis j= pool.getResource();
        //Jedis j= new Jedis("127.0.0.1",6379);
        j.select(4);//选择哪个库
        return j;
    }
}
